package activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import java.util.HashMap;

import top.yokey.android.R;
import top.yokey.android.base.BaseActivity;
import top.yokey.android.http.BaseCallBack;
import top.yokey.android.http.HttpHelp;


    public class LoginActivity extends BaseActivity {

        private AppCompatEditText mobileEditText;
        private AppCompatEditText passwordEditText;
        private AppCompatTextView loginTextView;
        private AppCompatTextView registerTextView;
        private View mobileView, passwordView;

        private SharedPreferences sharedPreferences;
        private SharedPreferences.Editor editor;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            setContentView(R.layout.activity_login);
            super.onCreate(savedInstanceState);
            String token = APP.get().getSharedPreferences().getSting("token", "");
            if (!token.isEmpty()) getMemberData();
        }

        private void getMemberData() {
        }

        @Override
        public void initView() {

            mobileEditText = findViewById(R.id.mobileEditText);
            passwordEditText = findViewById(R.id.passwordEditText);
            loginTextView = findViewById(R.id.loginTextView);
            registerTextView = findViewById(R.id.registerTextView);
            mobileView = findViewById(R.id.mobileView);
            passwordView = findViewById(R.id.passwordView);
            //初始化SharedPreferences存储
            sharedPreferences = getSharedPreferences("android", MODE_PRIVATE);
            editor = sharedPreferences.edit();
            //初始化网络请求框架
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("model", Build.MODEL);
            HttpHelp.get().init(getApplication(), "http://192.168.56.1/api/", hashMap);
            //测试代码，从SP对象中拿到键名为token的值
            System.out.println("系统中存储的token值为" + sharedPreferences.getString("token", ""));

        }

        @Override
        public void initEvent() {

            loginTextView.setOnClickListener(view -> {
                String mobile = mobileEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                if (mobile.isEmpty()) {
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.isEmpty()) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //防止多次点击
                loginTextView.setEnabled(false);//禁用按钮
                loginTextView.setText("正在登录...");//修改按钮文字
                //发送请求  15207713074 123456
                HttpHelp.get().ready("base", "login")
                        .add("mobile", mobile)
                        .add("password", password)
                        .get(new BaseCallBack() {
                            @Override
                            public void onSuccess(String data) {
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                loginTextView.setEnabled(true);// 启用按钮
                                loginTextView.setText("登录");//修改按钮文字
                                //SharedPreferences 存储token
                                App.get().getEditor().putString("token", data);
                                App.get().getEditor().commit();//这一句很重要，如果不执行 那么数据不会存储
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                App.get().setLogout(false);
                                finish();//结束当前活动
                                getMemberData();
                                //editor.putString("token", data);
                                //editor.commit();//这一句很重要，如果不执行 那么数据不会存储
                                //目前的token值 c5372123d26aaf638fe81a2845bb5d17
                            }

                            @Override
                            public void onFailure(String reason) {
                                Toast.makeText(LoginActivity.this, reason, Toast.LENGTH_SHORT).show();
                                loginTextView.setEnabled(true);// 启用按钮
                                loginTextView.setText("登录");//修改按钮文字
                            }
                        });
            });
            //编辑框的焦点事件

            mobileEditText.setOnFocusChangeListener((view, b) -> {
                if (b) {
                    mobileView.setBackgroundResource(R.color.primary);
                    passwordView.setBackgroundResource(R.color.textHint);
                }
            });

            passwordEditText.setOnFocusChangeListener((view, b) -> {
                if (b) {
                    mobileView.setBackgroundResource(R.color.textHint);
                    passwordView.setBackgroundResource(R.color.primary);
                }
            });

            registerTextView.setOnClickListener(view -> {
                //activity之间的跳转 使用intent，一定要确保目标activity已经在manifests文件注册
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                //数据回传
                startActivityForResult(intent, 999);
            });

        }


        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == 888 && requestCode == 999) {
                mobileEditText.setText(data.getStringExtra("mobile"));
            }
        }

        private void getMemberData() {

            HttpHelp.get().ready("member", "getMemberData")
                    .get(new BaseCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            App.get().setMemberData(new Gson().fromJson(data, MemberData.class));
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();//结束当前活动
                        }

                        @Override
                        public void onFailure(String reason) {
                            //网络请求失败，1：网络问题，重试
                            //2.后端返回错误：如果是token失效，重新登陆
                            if (reason.contains("登录")) {
                                Toast.makeText(LoginActivity.this, "请重新登录", Toast.LENGTH_SHORT).show();
                                App.get().setMemberData(null);
                                App.get().getEditor().putString("token", "");
                                App.get().getEditor().commit();
                            }
                        }
                    });

        }
    }

